/**
 * @class Ext.tree.DwrTreeLoader
 */
Ext.tree.DwrTreeLoader = function(conf){
    var config=conf||{};
    // set up the configuration
    this.loadFunc=conf.loadFunction;
	this.idField = conf.idField||'id';
	this.idPrefix = conf.idPrefix||'item';
	this.nameField = conf.nameField||'name';
	conf.url='dummyUrl';
	this.childProperty=conf.childProperty;
	this.loadArg=conf.loadParam; // TODO add a mechanism for passing params to DWR
	if(conf.blankLoadParam) {
		this.loadArg='DUMMY';
	}
    Ext.tree.DwrTreeLoader.superclass.constructor.call(this,conf);
};

Ext.extend(Ext.tree.DwrTreeLoader, Ext.tree.TreeLoader, {
    requestData : function(node, callback){
        if(this.fireEvent("beforeload", this, node, callback) !== false){
             var thisPane = this;
            this.transId = true;
            var args = [];
            if(this.loadArg && this.loadArg!==null) {
            	args[0]=this.loadArg!='DUMMY'?this.loadArg:'';
            }
	         args.push({
                callback: function(categories) { 
                        thisPane.onLoadElements(categories, node, callback); },
                errorHandler: function(message) { Ext.Msg.alert('Error',message); }
            });
            this.loadFunc.apply(this,args);
        }
        else{
            // if the load is cancelled, make sure we notify 
            // the node that we are done
            if(typeof callback == "function"){
                callback();
            }
        }
    },
    
    onLoadElements: function(elements, node, callback) {
        this.transId = false;
        for (var i = 0; i < elements.length; i++) {
            var el = elements[i];
            var children = el[this.childProperty];
            var childNodes = [];
            var j; 
            if(children) {
	            for(j=0;j<children.length;j++) {
	            	var chNode = children[j];
	            	childNodes.push({id:this.childProperty+'_'+chNode.id,
	            	text:chNode.name,
	            	leaf:true });
	            }
            }
            var nodeLabel = el[this.nameField];
            var elNode = this.createNode({ 
                                id: this.idPrefix+"_" + el[this.idField],
                                 text: nodeLabel,
                                 children:childNodes,
                              leaf: false });
            if(elNode){
                node.appendChild(elNode); 
            }
        }
        if(typeof callback == "function"){
            callback(this, node);
        }        
        var s = this.fireEvent("load", this, node);
    }
});